'use client';

import { useState, useEffect, useCallback } from 'react';
import { api, Video, VideoListParams, VideoListResponse, User } from '@/lib/api';
import { ApiError } from '@/lib/http';

// 通用API状态类型
export interface ApiState<T> {
  data: T | null;
  loading: boolean;
  error: ApiError | null;
}

// 分页状态类型
export interface PaginationState {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

// 通用API Hook
export function useApi<T>(
  apiCall: () => Promise<T>,
  dependencies: any[] = []
): ApiState<T> & { refetch: () => Promise<void> } {
  const [state, setState] = useState<ApiState<T>>({
    data: null,
    loading: true,
    error: null,
  });

  const fetchData = useCallback(async () => {
    setState(prev => ({ ...prev, loading: true, error: null }));
    
    try {
      const data = await apiCall();
      setState({ data, loading: false, error: null });
    } catch (error) {
      setState({ data: null, loading: false, error: error as ApiError });
    }
  }, dependencies);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return {
    ...state,
    refetch: fetchData,
  };
}

// 视频列表Hook
export function useVideoList(params?: VideoListParams) {
  const [videos, setVideos] = useState<Video[]>([]);
  const [pagination, setPagination] = useState<PaginationState>({
    page: 1,
    pageSize: 20,
    total: 0,
    totalPages: 0,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<ApiError | null>(null);

  const fetchVideos = useCallback(async (newParams?: VideoListParams) => {
    setLoading(true);
    setError(null);

    try {
      const finalParams = { ...params, ...newParams };
      const response = await api.getVideoList(finalParams);
      
      setVideos(response.videos);
      setPagination({
        page: response.page,
        pageSize: response.pageSize,
        total: response.total,
        totalPages: response.totalPages,
      });
    } catch (err) {
      setError(err as ApiError);
    } finally {
      setLoading(false);
    }
  }, [params]);

  // 加载更多
  const loadMore = useCallback(async () => {
    if (loading || pagination.page >= pagination.totalPages) return;

    setLoading(true);
    try {
      const response = await api.getVideoList({
        ...params,
        page: pagination.page + 1,
      });

      setVideos(prev => [...prev, ...response.videos]);
      setPagination({
        page: response.page,
        pageSize: response.pageSize,
        total: response.total,
        totalPages: response.totalPages,
      });
    } catch (err) {
      setError(err as ApiError);
    } finally {
      setLoading(false);
    }
  }, [params, pagination, loading]);

  // 刷新
  const refresh = useCallback(() => {
    fetchVideos({ ...params, page: 1 });
  }, [fetchVideos, params]);

  useEffect(() => {
    fetchVideos();
  }, [fetchVideos]);

  return {
    videos,
    pagination,
    loading,
    error,
    loadMore,
    refresh,
    fetchVideos,
  };
}

// 视频详情Hook
export function useVideoDetail(id: string) {
  return useApi(() => api.getVideoDetail(id), [id]);
}

// 视频搜索Hook
export function useVideoSearch() {
  const [results, setResults] = useState<Video[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<ApiError | null>(null);

  const search = useCallback(async (keyword: string, params?: VideoListParams) => {
    if (!keyword.trim()) {
      setResults([]);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await api.searchVideos(keyword, params);
      setResults(response.videos);
    } catch (err) {
      setError(err as ApiError);
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, []);

  const clear = useCallback(() => {
    setResults([]);
    setError(null);
  }, []);

  return {
    results,
    loading,
    error,
    search,
    clear,
  };
}

// 用户信息Hook
export function useCurrentUser() {
  return useApi(() => api.getCurrentUser(), []);
}

// 热门视频Hook
export function usePopularVideos(limit: number = 10) {
  return useApi(() => api.getPopularVideos(limit), [limit]);
}

// 最新视频Hook
export function useLatestVideos(limit: number = 10) {
  return useApi(() => api.getLatestVideos(limit), [limit]);
}

// 分类视频Hook
export function useCategoryVideos(category: string, params?: VideoListParams) {
  return useApi(() => api.getVideosByCategory(category, params), [category, params]);
}

// 文件上传Hook
export function useFileUpload() {
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<ApiError | null>(null);

  const upload = useCallback(async (file: File, type: 'video' | 'avatar' = 'video') => {
    setUploading(true);
    setProgress(0);
    setError(null);

    try {
      let result;
      if (type === 'video') {
        // 这里可以添加上传进度监听
        result = await api.uploadVideo(file, { title: file.name });
      } else {
        result = await api.uploadAvatar(file);
      }
      
      setProgress(100);
      return result;
    } catch (err) {
      setError(err as ApiError);
      throw err;
    } finally {
      setUploading(false);
    }
  }, []);

  return {
    uploading,
    progress,
    error,
    upload,
  };
}

// 导出所有类型
export type { ApiState, PaginationState };
